<?php
declare (strict_types = 1);

namespace app\mall\controller;


use app\BaseController;
use app\controller\api\system\plugins\Exception;
use Spatie\PdfToText\Pdf;
use think\facade\App;
use think\facade\Filesystem;
use think\facade\Request;

class PdfController extends BaseController
{
    public function index()
    {

        echo '1' . Request::server('REDIRECT_URL');//REDIRECT_URL
        echo '2' . Request::server('REQUEST_URI');//REQUEST_URI
        die;

        ini_set('memory_limit', -1);
        ini_set("max_execution_time", 0);

        $file = App::getRootPath() . 'public/storage/upload/20210304/00000081629F041.pdf';
        $new_file = App::getRootPath() . 'public/storage/upload/20210304/00000081629F041.txt';

        // 获取开始页数 指定页数:-f 1 -l 10 从1-10页
        $last_line = system("pdftotext -layout $pdf_file $txt_file",$return_var);
        if ($return_var) {
            return json(['code'=>0, 'message'=>$last_line]);
        }

        return json(['code'=>1, 'message'=>'Success']);
    }

    /**
     * 转换文件
     */
    public function pdf_to_text()
    {
        ini_set('memory_limit', -1);
        ini_set("max_execution_time", 0);

        $file       = Request::file('file');
        $first_page = Request::post('first_page', 0);
        $last_page  = Request::post('last_page', 0);

        if (!$file) {
            return json(['code'=>0, 'message'=>'file Error']);
        }

        //验证文件规则
        $result = validate(['file' => ['fileExt:pdf']])->check(['file' => $file]);
        if (!$result) {
            return json(['code'=>0, 'message'=>'Error']);
        }

        //上传到服务器
        $path = Filesystem::disk('public')->putFile('upload', $file);
        //结果是 $path = upload/20200825\***

        //路径，Filesystem::getDiskConfig('public','url')功能是获取public目录下的storage，
        $filePath = Filesystem::getDiskConfig('public','url').'/'.str_replace('\\','/',$path);
        //结果是 $picCover = storage/upload/20200825/***

        //获取名称
        $fileName = $file->getOriginalName();

        try {

            $txt_file = str_replace(".pdf", ".txt", $filePath);
            $pdfPath  = App::getRootPath() . 'public' . $filePath;

            if (!$first_page) {
                $str = (new Pdf())
                    ->setPdf($pdfPath)
                    ->setOptions(['layout', 'l 1'])
                    ->text();

                // Adjustments & Other Charges
                $end = stripos($str, 'Adjustments & Other Charges');
                $first_page = trim(substr($str,  $end - 12, 10));
                $first_page = str_replace(",", "", $first_page);
                if (!is_numeric($first_page)) {
                    throw new Exception('first_page is null');
                }
            }

            // 读取第一页 f 指定转换第一页,l 指定转换最后一页
            $options[] = "layout";
            $options[] = "f $first_page";
            if ($last_page) {
                $options[] = "l $last_page";
            }

            $text = (new Pdf())
                ->setPdf($pdfPath)
                ->setOptions($options)
                ->text();

            file_put_contents(App::getRootPath() . 'public' .$txt_file, $text . "\r\n", FILE_APPEND);
            @unlink($pdfPath);
            return json(['code'=>1, 'message'=>'success', 'data' => ['file' =>'http://'.$_SERVER['HTTP_HOST'] . $txt_file , 'name'=>$txt_file]]);
        } catch(\Exception $e) {
            return json(['code'=>0, 'message'=>$e->getMessage()]);
        }
    }

    /**
     * 删除文件
     */
    public function del_pdf_to_text()
    {
        $file = Request::param('name');
        $filename = App::getRootPath() . 'public' . $file;
        if (is_file($filename)) {
            @unlink($filename);
        }
        return json(['code'=>1, 'message'=>'success']);
    }
}
